﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;

using Microsoft.Office.Interop.Word;

namespace DusonFramework.Documents.Office.Word.Ms
{
    /// <summary>
    /// Word操作类
    /// 1.Microsoft.Office.Core（Com组件：Miscrosoft Office {Office版本号} Object Library）
    /// 2.Microsoft.Office.Interop.Word
    /// </summary>
    public class WordEx
    {
        private Application _word;
        private Document _doc;
        private object _missing = System.Reflection.Missing.Value;
        private object _endOfDoc = "\\endofdoc";

        public Application WordApplication
        {
            get { return _word; }
        }

        public WordEx()
        {
            _word = new Application();
        }

        public WordEx(Application wordapp)
        {
            _word = wordapp;
        }

        #region 文件操作

        public void Open(string filePath)
        {
            object fileName = filePath;
            object readOnly = false;
            object isVisible = true;

            _doc = _word.Documents.Open(ref fileName, ref _missing, ref readOnly,
                ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing,
                ref _missing, ref _missing, ref isVisible, ref _missing, ref _missing, ref _missing, ref _missing);

            _doc.Activate();
        }

        public void New()
        {
            this.New(string.Empty);
        }
        /// <summary>   
        /// 附加dot模版文件   
        /// </summary>   
        public void New(string dotFile)
        {
            object path = System.Reflection.Missing.Value;
            if (!string.IsNullOrWhiteSpace(dotFile))
                path = dotFile;
            _doc = _word.Documents.Add(ref path, ref _missing, ref _missing, ref _missing);
        }

        public void Save()
        {
            _doc.Save();
        }
        public void SaveAs(string filePath)
        {
            object FileName = filePath;
            object FileFormat = WdSaveFormat.wdFormatDocument;
            object LockComments = false;
            object AddToRecentFiles = true;
            object ReadOnlyRecommended = false;
            object EmbedTrueTypeFonts = false;
            object SaveNativePictureFormat = true;
            object SaveFormsData = true;
            object SaveAsAOCELetter = false;
            object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese;
            object InsertLineBreaks = false;
            object AllowSubstitutions = false;
            object LineEnding = WdLineEndingType.wdCRLF;
            object AddBiDiMarks = false;

            //_doc.SaveAs(ref FileName, ref FileFormat, ref LockComments,
            //    ref missing, ref AddToRecentFiles, ref missing,
            //    ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,
            //    ref SaveNativePictureFormat, ref SaveFormsData,
            //    ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks,
            //    ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);

            _doc.SaveAs(ref FileName, ref _missing, ref _missing,
                ref _missing, ref _missing, ref _missing,
                ref _missing, ref _missing,
                ref _missing, ref _missing,
                ref _missing, ref Encoding, ref _missing,
                ref _missing, ref _missing, ref _missing);
        }
        public void SaveAsHtml(string filePath)
        {
            object fileName = filePath;
            object Format = (int)WdSaveFormat.wdFormatHTML;
            _doc.SaveAs(ref fileName, ref Format, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing,
                ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing, ref _missing);
        }

        public void Close()
        {
            this.Close(true);
        }
        public void Close(bool isSave)
        {
            object saveOption = isSave ? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
            _doc.Close(ref saveOption, ref _missing, ref _missing);

            // 关闭wordApp组件对象 
            this.Quit();
        }

        public void Quit()
        {
            this.Quit(true);
        }
        public void Quit(bool isSave)
        {
            object saveOption = isSave ? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
            _word.Quit(ref saveOption, ref _missing, ref _missing);
        }

        #endregion

        #region 页面设置

        public void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
        {
            _doc.PageSetup.PageWidth = _word.CentimetersToPoints((float)width);
            _doc.PageSetup.PageHeight = _word.CentimetersToPoints((float)height);
            if (orientation == Orientation.Landscape)
            {
                _doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
            }
            _doc.PageSetup.TopMargin = (float)(topMargin * 25); //上边距             
            _doc.PageSetup.LeftMargin = (float)(leftMargin * 25); //左边距             
            _doc.PageSetup.RightMargin = (float)(rightMargin * 25); //右边距             
            _doc.PageSetup.BottomMargin = (float)(bottomMargin * 25); //下边距        
        }
        public void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
        {
            SetPage(orientation, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
        }
        public void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
        {
            SetPage(Orientation.Portrait, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
        }
        public void SetOrientation(Orientation orientation)
        {
            if (orientation == Orientation.Landscape)
                _doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
            else if(orientation == Orientation.Portrait)
                _doc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;
        }

        #endregion

        #region 添加菜单(工具栏)项

        //添加单独的菜单项   
        public void AddMenu(Microsoft.Office.Core.CommandBarPopup popuBar)
        {
            Microsoft.Office.Core.CommandBar menuBar = null;
            menuBar = this._word.CommandBars["Menu Bar"];
            popuBar = (Microsoft.Office.Core.CommandBarPopup)this._word.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlPopup, _missing, popuBar.Tag, true);
            if (popuBar == null)
            {
                popuBar = (Microsoft.Office.Core.CommandBarPopup)menuBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup, _missing, _missing, _missing, _missing);
            }
        }

        //添加单独工具栏   
        public void AddToolItem(string strBarName, string strBtnName)
        {
            Microsoft.Office.Core.CommandBar toolBar = null;
            toolBar = (Microsoft.Office.Core.CommandBar)this._word.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, _missing, strBarName, true);
            if (toolBar == null)
            {
                toolBar = (Microsoft.Office.Core.CommandBar)this._word.CommandBars.Add(
                     Microsoft.Office.Core.MsoControlType.msoControlButton,
                     _missing, _missing, _missing);
                toolBar.Name = strBtnName;
                toolBar.Visible = true;
            }
        }

        #endregion

        #region 移动光标位置

        // Go to a predefined bookmark, if the bookmark doesn't exists the application will raise an error   
        public void GotoBookMark(string strBookMarkName)
        {
            // VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"   
            object Bookmark = (int)WdGoToItem.wdGoToBookmark;
            object NameBookMark = strBookMarkName;
            _word.Selection.GoTo(ref Bookmark, ref _missing, ref _missing, ref NameBookMark);
        }

        public void GoToTheEnd()
        {
            // VB :  Selection.EndKey Unit:=wdStory   
            object unit;
            unit = WdUnits.wdStory;
            _word.Selection.EndKey(ref unit, ref _missing);
        }

        public void GoToLineEnd()
        {
            object unit = WdUnits.wdLine;
            object ext = WdMovementType.wdExtend;
            _word.Selection.EndKey(ref unit, ref ext);
        }

        public void GoToTheBeginning()
        {
            // VB : Selection.HomeKey Unit:=wdStory   
            object unit;
            unit = WdUnits.wdStory;
            _word.Selection.HomeKey(ref unit, ref _missing);
        }

        public void GoToTheTable(int ntable)
        {
            object what;
            what = WdUnits.wdTable;
            object which;
            which = WdGoToDirection.wdGoToFirst;
            object count;
            count = 1;
            _word.Selection.GoTo(ref what, ref which, ref count, ref _missing);
            _word.Selection.Find.ClearFormatting();

            _word.Selection.Text = "";
        }

        public void GoToRightCell()
        {
            // Selection.MoveRight Unit:=wdCell   
            object direction;
            direction = WdUnits.wdCell;
            _word.Selection.MoveRight(ref direction, ref _missing, ref _missing);
        }

        public void GoToLeftCell()
        {
            // Selection.MoveRight Unit:=wdCell   
            object direction;
            direction = WdUnits.wdCell;
            _word.Selection.MoveLeft(ref direction, ref _missing, ref _missing);
        }

        public void GoToDownCell()
        {
            object direction = WdUnits.wdLine;
            _word.Selection.MoveDown(ref direction, ref _missing, ref _missing);
        }

        public void GoToUpCell()
        {
            object direction = WdUnits.wdLine;
            _word.Selection.MoveUp(ref direction, ref _missing, ref _missing);
        }

        #endregion

        #region 插入操作

        public void InsertLineBreak()
        {
            _word.Selection.TypeParagraph();
        }

        /// <summary>   
        /// 插入多个空行   
        /// </summary>   
        /// <param name="nline"></param>   
        public void InsertLineBreak(int nline)
        {
            for (int i = 0; i < nline; i++)
                _word.Selection.TypeParagraph();
        }

        public void InsertLine(float left, float top, float width, float weight, int r, int g, int b)
        {
            object Anchor = _word.Selection.Range;
            object rep = false;
            left = _word.CentimetersToPoints(left);
            top = _word.CentimetersToPoints(top);
            width = _word.CentimetersToPoints(width);
            Shape s = _word.ActiveDocument.Shapes.AddLine(0, top, width, top, ref Anchor);
            s.Line.ForeColor.RGB = RGB(r, g, b);
            s.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
            s.Line.Style = Microsoft.Office.Core.MsoLineStyle.msoLineSingle;
            s.Line.Weight = weight;
        }

        /// <summary>
        /// 插入分页符
        /// </summary>
        public void InsertPagebreak()
        {
            object pBreak = (int)WdBreakType.wdPageBreak;
            _word.Selection.InsertBreak(ref pBreak);

            // 方法2
            //Paragraph para = _doc.Content.Paragraphs.Add(ref _missing);
            //object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
            //para.Range.InsertBreak(ref pBreak);
        }

        // 插入页码   
        public void InsertPageNumber()
        {
            this.InsertPageNumber(Alignment.Center);
        }
        // 插入页码   
        public void InsertPageNumber(Alignment align)
        {
            object wdFieldPage = WdFieldType.wdFieldPage;
            object preserveFormatting = true;
            _word.Selection.Fields.Add(_word.Selection.Range, ref wdFieldPage, ref _missing, ref preserveFormatting);
            SetAlignment(align);
        }
        /// <summary>
        /// 插入页码
        /// </summary>
        /// <param name="format">样式</param>
        /// <param name="align">格式</param>
        public void InsertAllPageNumber(string format, string align)
        {
            object IncludeFootnotesAndEndnotes = false;
            int pageSum = _doc.ComputeStatistics(WdStatistic.wdStatisticPages, ref IncludeFootnotesAndEndnotes);
            GoToTheBeginning();
            for (int i = 0; i < pageSum; i++)
            {
                InsertPageNumber();
                _doc.Application.Browser.Next();//下一页
            }
        }

        /// <summary>
        /// 添加页眉
        /// </summary>
        /// <param name="content">页眉内容</param>
        /// <param name="align">对齐文式</param>
        public void InsertHeader(string content, Alignment align)
        {
            _word.ActiveWindow.View.Type = WdViewType.wdOutlineView;
            _word.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(content);
            SetAlignment(align);// 设置右对齐
            _word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; // 跳出页眉设置
        }
        /// <summary>
        /// 添加页脚
        /// </summary>
        /// <param name="content">页脚内容</param>
        /// <param name="align">对齐文式</param>
        public void InsertFooter(string content, Alignment align)
        {
            _word.ActiveWindow.View.Type = WdViewType.wdOutlineView;
            _word.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;
            _word.ActiveWindow.ActivePane.Selection.InsertAfter(content);
            SetAlignment(align);// 设置对齐
            _word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
        }

        public void InsertText(string strText)
        {
            if (string.IsNullOrWhiteSpace(strText)) return;

            _word.Selection.TypeText(strText);

            // 方法2
            //Range rng = _doc.Content;
            //rng.Text = strText;

            // 方法3
            //Paragraph oPara = _doc.Content.Paragraphs.Add(ref missing);
            //oPara.Range.Text = strText;
            //oPara.Range.InsertParagraphAfter();
        }

        #region 追加文字

        /// <summary>
        /// 追加标题1
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineOne(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Times New Roman", 22f, System.Drawing.FontStyle.Bold);
            ParagraphFormat format = new ParagraphFormat(17f, 16.5f, 0f, 0f, 2.41f);
            AppendText(text, font, format);
        }
        /// <summary>
        /// 追加标题2
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineTwo(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Arial", 16f, System.Drawing.FontStyle.Bold);
            ParagraphFormat format = new ParagraphFormat(13f, 13f, 0f, 0f, 1.73f);
            AppendText(text, font, format);
        }
        /// <summary>
        /// 追加标题3
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendHeadLineThree(string text)
        {
            System.Drawing.Font font = new System.Drawing.Font("Times New Roman", 16f, System.Drawing.FontStyle.Bold);
            ParagraphFormat format = new ParagraphFormat(13f, 13f, 0f, 0f, 1.73f);
            AppendText(text, font);
        }

        /// <summary>
        /// 追加正文
        /// </summary>
        /// <param name="text">The text.</param>
        public void AppendText(string text)
        {
            this.AppendText(text, null, null);
        }
        /// <summary>
        /// Appends the text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="font">The font.</param>
        public void AppendText(string text, System.Drawing.Font font)
        {
            if (font == null)
                font = new System.Drawing.Font("Times New Roman", 10.5f);
            this.AppendText(text, font, null);
        }
        /// <summary>
        /// 在文章后添加段落。使用Word格式
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="font">The font.</param>
        /// <param name="textAlign">The text align.</param>
        public void AppendText(string text, System.Drawing.Font font, ParagraphFormat format)
        {
            if (_doc == null)
                return;
            if (font == null)
                font = new System.Drawing.Font("Times New Roman", 10.5f);
            if (format == null)
                format = new ParagraphFormat();

            Paragraph oPara;

            //Set Text
            oPara = _doc.Content.Paragraphs.Add(ref _missing);
            if (text != null && text != "")
                oPara.Range.Text = text;

            //Set Text Format
            oPara.Range.Font.Size = font.Size;
            try { oPara.Range.Font.Name = font.Name; }
            catch { oPara.Range.Font.Name = "Times New Roman"; }
            oPara.Range.Font.Italic = font.Italic ? 1 : 0;
            oPara.Range.Font.Bold = font.Bold ? 1 : 0;

            //Set Paragraph
            oPara.Alignment = format.Alignment;

            if (format.SpaceAfterAuto > 0)
                oPara.SpaceAfter = format.SpaceAfter;
            else
                oPara.SpaceAfter = 0f;

            if (format.SpaceBeforeAuto > 0)
                oPara.SpaceBefore = format.SpaceBefore;
            else
                oPara.SpaceBefore = 0f;

            oPara.LeftIndent = format.LeftIndent;
            oPara.RightIndent = format.RightIndent;
            oPara.FirstLineIndent = format.FirstLineIndent;
            //if (format.MultiLineSpace)
            //{
            //    oPara.LineSpacingRule = WdLineSpacing.wdLineSpaceMultiple;
            //    oPara.LineSpacing = format.LineSpacing;
            //}
            //else
            //{
            //    oPara.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle;
            //}

            oPara.Range.InsertParagraphAfter();
        }

        #endregion

        public void InsertImage(string filePath, float width, float height)
        {
            string FileName = filePath;
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = _doc.Bookmarks.get_Item(ref _endOfDoc).Range;
            _word.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor).Select();

            _word.Selection.InlineShapes[1].Width = width; // 图片宽度    
            _word.Selection.InlineShapes[1].Height = height; // 图片高度

            // 将图片设置为四面环绕型
            Shape s = _word.Selection.InlineShapes[1].ConvertToShape();
            s.WrapFormat.Type = WdWrapType.wdWrapInline;
        }

        #region 表格

        /// <summary>
        /// 插入表
        /// </summary>
        /// <param name="numRows">The num rows.</param>
        /// <param name="numColumns">The num columns.</param>
        public Table InsertTable(int numRows, int numColumns)
        {
            if (_doc == null)
                return null;

            Range range = _doc.Bookmarks.get_Item(ref _endOfDoc).Range;
            Table table = _doc.Tables.Add(range, numRows, numColumns, ref _missing, ref _missing);

            return table;
        }
        public void SetTable(int tableIndex, int rows, int columns, string content, Color color, Alignment align)
        {
            if (tableIndex > _doc.Tables.Count)
                tableIndex = _doc.Tables.Count;
            Table table = _doc.Tables[tableIndex];
            table.Cell(rows, columns).Range.Font.Color = this.GetWdColor(color);
            table.Cell(rows, columns).Range.Text = content;
            table.Range.ParagraphFormat.Alignment = GetWdParagraphAlignment(align);
        }
        public void MergeColumns(int tableIndex, int rows1, int rows2, int columns)
        {
            if (tableIndex > _doc.Tables.Count)
                tableIndex = _doc.Tables.Count;
            Table table = _doc.Tables[tableIndex];
            table.Cell(rows1, columns).Merge(table.Cell(rows2, columns));
        }
        public void SplitColumns(int tableIndex, int rows1, int columns1, int rows2, int columns2)
        {
            if (tableIndex > _doc.Tables.Count)
                tableIndex = _doc.Tables.Count;
            Table table = _doc.Tables[tableIndex];
            object row = rows2;
            object col = columns2;
            table.Cell(rows1, columns1).Split(ref row, ref col);
        }

        #endregion

        #endregion

        #region 设置样式

        /// <summary>   
        /// Change the paragraph alignement   
        /// </summary>   
        /// <param name="align"></param>   
        public void SetAlignment(Alignment align)
        {
            _word.Selection.ParagraphFormat.Alignment = this.GetWdParagraphAlignment(align);
        }

        public void SetFont(string type)
        {
            switch (type)
            {
                case "Bold":
                    _word.Selection.Font.Bold = 1;
                    break;
                case "Italic":
                    _word.Selection.Font.Italic = 1;
                    break;
                case "Underlined":
                    _word.Selection.Font.Subscript = 0;
                    break;
            }
        }

        public void ResetFont()
        {
            _word.Selection.Font.Bold = 0;
            _word.Selection.Font.Italic = 0;
            _word.Selection.Font.Subscript = 0;
        }
        public static void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
        {
            wordFont.Name = font.Name;
            wordFont.Size = font.Size;
            if (font.Bold) { wordFont.Bold = 1; }
            if (font.Italic) { wordFont.Italic = 1; }
            if (font.Underline == true)
            {
                wordFont.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
            }
            wordFont.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
            if (font.Strikeout)
            {
                wordFont.StrikeThrough = 1; // 删除线         
            }
        }

        public void SetFontName(string strType)
        {
            _word.Selection.Font.Name = strType;
        }

        public void SetFontSize(float nSize)
        {
            SetFontSize(nSize, 100);
        }

        public void SetFontSize(float nSize, int scaling)
        {
            if (nSize > 0f)
                _word.Selection.Font.Size = nSize;
            if (scaling > 0)
                _word.Selection.Font.Scaling = scaling;
        }

        public void SetFontColor(string strFontColor)
        {
            switch (strFontColor.ToLower())
            {
                case "blue":
                    _word.Selection.Font.Color = WdColor.wdColorBlue;
                    break;
                case "gold":
                    _word.Selection.Font.Color = WdColor.wdColorGold;
                    break;
                case "gray":
                    _word.Selection.Font.Color = WdColor.wdColorGray875;
                    break;
                case "green":
                    _word.Selection.Font.Color = WdColor.wdColorGreen;
                    break;
                case "lightblue":
                    _word.Selection.Font.Color = WdColor.wdColorLightBlue;
                    break;
                case "orange":
                    _word.Selection.Font.Color = WdColor.wdColorOrange;
                    break;
                case "pink":
                    _word.Selection.Font.Color = WdColor.wdColorPink;
                    break;
                case "red":
                    _word.Selection.Font.Color = WdColor.wdColorRed;
                    break;
                case "yellow":
                    _word.Selection.Font.Color = WdColor.wdColorYellow;
                    break;
            }
        }

        public void SetPageNumberAlign(string strType, bool bHeader)
        {
            object alignment;
            object bFirstPage = false;
            object bF = true;
            //if (bHeader == true)   
            //WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF;   
            switch (strType)
            {
                case "Center":
                    alignment = WdPageNumberAlignment.wdAlignPageNumberCenter;
                    //WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage);   
                    //Selection objSelection = WordApplic.pSelection;   
                    _word.Selection.HeaderFooter.PageNumbers[1].Alignment = WdPageNumberAlignment.wdAlignPageNumberCenter;
                    break;
                case "Right":
                    alignment = WdPageNumberAlignment.wdAlignPageNumberRight;
                    _word.Selection.HeaderFooter.PageNumbers[1].Alignment = WdPageNumberAlignment.wdAlignPageNumberRight;
                    break;
                case "Left":
                    alignment = WdPageNumberAlignment.wdAlignPageNumberLeft;
                    _word.Selection.HeaderFooter.PageNumbers.Add(ref alignment, ref bFirstPage);
                    break;
            }
        }

        #endregion

        #region 替换

        ///<summary>   
        /// 在word 中查找一个字符串直接替换所需要的文本   
        /// </summary>   
        /// <param name="strOldText">原文本</param>   
        /// <param name="strNewText">新文本</param>   
        /// <returns></returns>   
        public bool Replace(string strOldText, string strNewText)
        {
            if (_doc == null)
                _doc = _word.ActiveDocument;
            this._doc.Content.Find.Text = strOldText;
            object FindText, ReplaceWith, Replace;//    
            FindText = strOldText;//要查找的文本   
            ReplaceWith = strNewText;//替换文本   
            Replace = WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。  
                                                      * wdReplaceNone - 不替换找到的任何项。  
                                                    * wdReplaceOne - 替换找到的第一项。  
                                                    * */
            _doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置   
            if (_doc.Content.Find.Execute(
                ref FindText, ref _missing,
                ref _missing, ref _missing,
                ref _missing, ref _missing,
                ref _missing, ref _missing, ref _missing,
                ref ReplaceWith, ref Replace,
                ref _missing, ref _missing,
                ref _missing, ref _missing))
            {
                return true;
            }
            return false;
        }

        public bool SearchReplace(string strOldText, string strNewText)
        {
            object replaceAll = WdReplace.wdReplaceAll;

            //首先清除任何现有的格式设置选项，然后设置搜索字符串 strOldText。   
            _word.Selection.Find.ClearFormatting();
            _word.Selection.Find.Text = strOldText;

            _word.Selection.Find.Replacement.ClearFormatting();
            _word.Selection.Find.Replacement.Text = strNewText;

            if (_word.Selection.Find.Execute(
                ref _missing, ref _missing, ref _missing, ref _missing, ref _missing,
                ref _missing, ref _missing, ref _missing, ref _missing, ref _missing,
                ref replaceAll, ref _missing, ref _missing, ref _missing, ref _missing))
            {
                return true;
            }
            return false;
        }

        #endregion

        #region 读取相关

        /// <summary>
        /// 读取第i段内容
        /// </summary>
        /// <param name="i">段索引</param>
        /// <returns>string</returns>
        public string readParagraph(int i)
        {
            try
            {
                string temp = _doc.Paragraphs[i].Range.Text.Trim();
                return temp;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 获得总段数
        /// </summary>
        /// <returns>int</returns>
        public int getParCount()
        {
            return _doc.Paragraphs.Count;
        }

        #endregion

        #region 私有方法

        /// <summary>   
        /// 设置页面为标准A4公文样式   
        /// </summary>   
        private void SetA4PageSetup()
        {
            _word.ActiveDocument.PageSetup.TopMargin = _word.CentimetersToPoints(3.7f);
            //oWordApplic.ActiveDocument.PageSetup.BottomMargin = oWordApplic.CentimetersToPoints(1f);   
            _word.ActiveDocument.PageSetup.LeftMargin = _word.CentimetersToPoints(2.8f);
            _word.ActiveDocument.PageSetup.RightMargin = _word.CentimetersToPoints(2.6f);
            //oWordApplic.ActiveDocument.PageSetup.HeaderDistance = oWordApplic.CentimetersToPoints(2.5f);   
            //oWordApplic.ActiveDocument.PageSetup.FooterDistance = oWordApplic.CentimetersToPoints(1f);   
            _word.ActiveDocument.PageSetup.PageWidth = _word.CentimetersToPoints(21f);
            _word.ActiveDocument.PageSetup.PageHeight = _word.CentimetersToPoints(29.7f);
        }

        private WdParagraphAlignment GetWdParagraphAlignment(Alignment align)
        {
            switch (align)
            {
                case Alignment.Center:
                    return WdParagraphAlignment.wdAlignParagraphCenter;

                case Alignment.Left:
                    return WdParagraphAlignment.wdAlignParagraphLeft;

                case Alignment.Right:
                    return WdParagraphAlignment.wdAlignParagraphRight;

                case Alignment.Justify:
                    return WdParagraphAlignment.wdAlignParagraphJustify;

                default:
                    return WdParagraphAlignment.wdAlignParagraphLeft;
            }
        }

        #region 颜色

        /// <summary>   
        /// rgb转换函数   
        /// </summary>   
        /// <param name="r"></param>   
        /// <param name="g"></param>   
        /// <param name="b"></param>   
        /// <returns></returns>   
        private int RGB(int r, int g, int b)
        {
            return ((b << 16) | (ushort)(((ushort)g << 8) | r));
        }

        /// <summary>
        /// RGBToColor
        /// </summary>
        /// <param name="color">颜色值</param>
        /// <returns>Color</returns>
        private Color RGBToColor(int color)
        {
            int r = 0xFF & color;
            int g = 0xFF00 & color;
            g >>= 8;
            int b = 0xFF0000 & color;
            b >>= 16;
            return Color.FromArgb(r, g, b);
        }

        private WdColor GetWdColor(Color color)
        {
            return (WdColor)(color.B * 65536) + (color.G * 256) + color.R;
        }

        #endregion

        #endregion

    }
}
